package com.yx.frame.service;

import java.math.BigDecimal;
import org.json.JSONObject;
import com.yx.frame.authority.User;

public final class Action {
	int id = 0;
	String name = null;
	String service = null;
	String method = null;
	String comment = null;
	long totalAccessNumber = 0;
	long totalAccessTime = 0;
	ActionMethod actionMethod = null;

	public Action(int id, String name, String service, String method,
			String comment) {
		this.id = id;
		this.name = name;
		this.service = service;
		this.method = method;
		this.comment = comment;
	}

	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public String getService() {
		return service;
	}

	public String getMethod() {
		return method;
	}

	public String getComment() {
		return comment;
	}

	public long getTotalAccessNumber() {
		return totalAccessNumber;
	}

	public long getTotalAccessTime() {
		return totalAccessTime;
	}

	public void setActionMethod(ActionMethod actionMethod) {
		this.actionMethod = actionMethod;
	}

	public double getAverageAccessTime() {
		if (totalAccessNumber == 0)
			return 0.00;
		double dTotalAccessTime = totalAccessTime;
		double toTalAccessNumber = totalAccessNumber;
		double averageTime = dTotalAccessTime / toTalAccessNumber;
		BigDecimal b = new BigDecimal(Double.toString(averageTime));
		return b.setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue();
	}

	public ServiceResult doActionMethod(User user, JSONObject obj,
			ServiceError error) throws Exception {
		long beginTime = 0;
		if (ActionManager.isPerformanceMonitor) {
			beginTime = System.currentTimeMillis();
		}
		if (actionMethod == null) {
			error.setErrorMessage("方法执行对象为空");
			return error;
		}
		try {
			ServiceResult ret = actionMethod.doAction(user, obj);			
			return ret;
		} catch (Exception ex) {			
			error.setErrorMessage(ex.getMessage());
			return error;
		}finally{
			if (ActionManager.isPerformanceMonitor) {
				totalAccessNumber++;
				totalAccessTime = totalAccessTime+(System.currentTimeMillis() - beginTime);
			}else{
				totalAccessNumber=0;
				totalAccessTime=0;
			}
		}
	}

}
